<template>
  <!-- 自定义搜索栏 -->
  <CustomNavbar />
  <!-- 滚动容器 -->
  <scroll-view
    class="scroll-view"
    scroll-y
    @scrolltolower="onScrolltolower"
    refresher-enabled
    @refresherrefresh="onRefresherrefresh"
    :refresher-triggered="isTriggered"
  >
    <!-- 骨架屏 -->
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!-- 轮播图 -->
      <XtxSwiper :bannerList="bannerList" />

      <!-- 前台分类 -->
      <CategoryPanel :categoryList="categoryList" />

      <!-- 热门推荐 -->
      <HotPanel :hotList="hotList" />

      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getHomeBannerAPI, getHomeCategoryAPI, getHotAPI } from '@/services/home'

// 骨架屏
import PageSkeleton from './components/PageSkeleton.vue'
// 引入自定义组件（顶部搜索栏）
import CustomNavbar from './components/CustomNavbar.vue'
// 轮播组件
import XtxSwiper from '@/components/XtxSwiper.vue'
// 前台组件
import CategoryPanel from './components/CategoryPanel.vue'
// 热门推荐
import HotPanel from './components/HotPanel.vue'
// 猜你喜欢（通用组件）
import XtxGuess from '@/components/XtxGuess.vue'

// 轮播图
const bannerList = ref([])
// 前台分类
const categoryList = ref([])
// 热门推荐
const hotList = ref([])
// 骨架屏加载中
const isLoading = ref(true)

// 获取轮播图数据
const getHomeBanner = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}

// 获取前台分类数据
const getHomeCategory = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}

// 获取热门推荐数据
const getHot = async () => {
  const res = await getHotAPI()
  hotList.value = res.result
}

// 获取猜你喜欢组件实例
const guessRef = ref()
// 滚动容器，滚动触底
const onScrolltolower = () => {
  if (guessRef.value.finish) {
    // 分页没结束
    guessRef.value.getGoodsGuessLike()
  } else {
    uni.showToast({
      icon: 'none',
      title: '没有更多数据了~',
    })
  }
}

// 滚动容器，下拉刷新触发动画
const isTriggered = ref(false)
const onRefresherrefresh = async () => {
  // 开始下拉刷新动画
  isTriggered.value = true
  // 重置猜你喜欢数据
  guessRef.value.resetDate()
  // 加载数据，请求同时发送
  await Promise.all([
    getHomeBanner(),
    getHomeCategory(),
    getHot(),
    guessRef.value.getGoodsGuessLike(),
  ])
  // 结束下拉刷新动画
  isTriggered.value = false
}

onLoad(async () => {
  await Promise.all([getHomeBanner(), getHomeCategory(), getHot()])
  isLoading.value = false
})
</script>

<style lang="scss">
// 底色
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.croll-view {
  flex: 1;
}
</style>
